package tradeDate

import (
	_ "embed"
	"github.com/gogf/gf/v2/os/gtime"
	"slices"
	"strings"
	"time"
)

//go:embed trade.json
var trades string
var dates []string
var dataIndex = make(map[string]int)

func init() {
	dates = strings.Split(trades, ",")
	for i, date := range dates {
		date = strings.TrimSpace(date)
		dates[i] = date
		dataIndex[date] = i
	}
}

func GetLatestDay() string {
	format := gtime.Now().Format("Y-m-d")
	// 如果今天是交易日, 返回今日时间
	if slices.Contains(dates, format) {
		return format
	}
	// 如果今天不是交易日, 判断前一天是否是
	days := 1
	for {
		s := gtime.Now().Add(-time.Hour * 24 * time.Duration(days)).Format("Y-m-d")
		if slices.Contains(dates, s) {
			return s
		}
		days++
	}
}

// 最近X交易日
func GetTradeDays(number int) (startDate string, endDate string) {
	endDate = GetLatestDay()
	if index, ok := dataIndex[endDate]; ok {
		if index >= number {
			startDate = dates[index-number]
		}
	}
	return
}

func GetStartTradeDay(tradeDate string, number int) (startDate string) {
	if index, ok := dataIndex[tradeDate]; ok {
		if index >= number {
			startDate = dates[index-number]
		}
	}
	return
}
